package org.example;

import lombok.extern.slf4j.Slf4j;
import org.example.Util.Sleeper;

import java.io.IOException;
import java.util.List;

@Slf4j(topic = "c.Main")
public class Main {

    //线程1 等待 线程2的下载结果
//    public static void main2(String[] args) {
//        GuardedObject go = new GuardedObject();
//        new Thread(()->{
//            //等待结果
//            log.debug("等待下载");
//            List<String> response = (List<String>) go.get();
//
//            log.debug("结果的大小是:{}", response.size());
//        }, "t1").start();
//
//        new Thread(()->{
//            //执行下载
//            log.debug("执行下载");
//            try {
//                List<String> download = DownLoader.download();
//                go.complete(download);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }, "t2").start();
//    }

    //测试保护暂停-增加超时功能
    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(()->{
            log.debug("begin");
            Object object = guardedObject.get(2000);//等待2s
            log.debug("结果是:{}", object);
        },"t1").start();

        new Thread(()->{
            log.debug("begin");
            //睡眠1s
            Sleeper.sleep(1);
            guardedObject.complete(null);
        }, "t2").start();
    }
}
class GuardedObject{
    //结果
    private Object response;

    //获取结果
    //timeout表示要等待多久
    public Object get(long timeout){
        synchronized (this){
            //没有结果
            //开始时间
            long begin = System.currentTimeMillis();
            long passTime = 0;//经历时间
            while (response == null){
                long waitTime = timeout - passTime;
                //经历时间超过了最大等待时间退出循环
                if (waitTime <= 0){
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //求得经历时间
                passTime = System.currentTimeMillis() - begin;
            }
            return response;
        }
    }

    //产生结果
    public void complete(Object response){
        synchronized (this){
            //给结果成员变量赋值
            this.response = response;
            this.notifyAll();
        }
    }
}